// miniprogram/pages/register/register.js
const app = getApp()
import {
  isEmpty
} from './../../utils/utils.js'
import {
  addUser
} from './../../api/users.js'
import {
  addSolitaireInfo
} from './../../api/solitaire_info'
import {
  updateNum
} from './../../api/solitaire'
import {
  callApi
} from './../../api/api'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    imgUrls: [], //选择的图片
    actId: null, //接龙活动id
    name: null, //姓名
    tel: null, //电话
    desc: null //备注
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log("options", options)
    this.data.actId = options._id
    this.data.title = options.title
    const act = options.act
    wx.setNavigationBarTitle({
      title: act + '登记详情',
    })
    this.setData({
      canIUseGetUserProfile: app.globalData.canIUseGetUserProfile
    })

  },
  //获取用户名称
  handlerNameInput(e) {
    this.data.name = e.detail.value
  },
  //获取电话
  handlerTelInput(e) {
    this.data.tel = e.detail.value
  },
  //获取备注
  handlerDescInput(e) {
    this.data.desc = e.detail.value
  },
  //兼容低版本获取用户信息
  handlerUserInfo(e) {
    const userInfo = e.detail.userInfo
    if (isEmpty(userInfo)) {
      wx.showToast({
        title: '授权失败',
        icon: 'error'
      })
      return
    }
    if (isEmpty(app.globalData.userInfo)) {
      addUser(userInfo).then(res => {
        //用户信息保存到缓存，下次不用授权了
        app.globalData.userInfo = userInfo
        this.create()
      })
    } else {
      this.handlerSumbit()
    }
  },
  hanlderUserInfoProfile() {
    //当前没有用户信息，授权获取用户信息
    if (isEmpty(app.globalData.userInfo)) {
      wx.getUserProfile({
        desc: '获取头像和昵称'
      }).then(res => {
        this.getUserInfo({
          detail: {
            userInfo: res.userInfo
          }
        })

      }).catch(res => {
        //拒绝授权
        this.getUserInfo({
          detail: {
            userInfo: undefined
          }
        })
      })
    } else {
      this.handlerSumbit()
    }
  },
  //提交报名信息
  handlerSumbit() {
    console.log("提交")
    if (isEmpty(this.data.name)) {
      wx.showToast({
        title: '请填写姓名',
        icon: "error"
      })
      return
    }
    const templId = "64fTw5szN79BlCWz745f8syYm_UmNVNx14U7QRWSGXc"
    wx.requestSubscribeMessage({
      tmplIds: [
        templId, //模板
      ]
    }).then(res => {
      const accept = res[templId] == 'accept' //是否同意

      wx.showLoading({
        title: '请稍等...',
      })
      const promises = []
      if (this.data.imgUrls.length) {
        this.data.imgUrls.forEach(filePath => {

          const cloudPath = `solitaire-image/${Date.now()}-${Math.random(0, 1) * 100000}` + filePath.match(/.[^.]+?$/)[0]
          promises.push(wx.cloud.uploadFile({
            cloudPath,
            filePath,
          }))
        })
      }
      Promise.all(promises).then(res => {
        console.log("upload", res)
        const data = {
          imgUrls: res.map(item => item.fileID), //选择的图片
          actId: this.data.actId, //接龙活动id
          name: this.data.name, //姓名
          tel: this.data.tel, //电话
          desc: this.data.desc //备注
        }

        return addSolitaireInfo(data)
      }).then(res => {
        return updateNum(this.data.actId)
      }).then(res => {
        wx.hideLoading()
        console.log('成功', res)
       
        const actId = this.data.actId
        const title = this.data.title

        if (accept) {
          callApi('subscribeMsg', '', {
            templateId: templId,
            path: "deital?_id=" + actId,
            title: title
          }).then(res => {
            console.log("订阅消息发送成功", res)
          }).catch(res => {
            console.log("订阅消息发送失败", res)
          })
        }
        wx.navigateBack({
          delta: 1,
        })
      }).catch(res => {
        wx.hideLoading()
        console.log('失败', res)
      })

    }).catch(res => {
      console.log("订阅消息API调用失败：", res)
    })


  },
  //图片
  onSelectChange(e) {
    console.log("onSelectChange", e.detail)
    this.data.imgUrls = e.detail
  }
})